<?php
class UpdateUserForm extends CFormModel
{
    public $display_name;
    public $home_page;
    public $role;
    public $username;
    public $email;
    public $newpass;
    public $newpass1;
    /**
     * @var $user User
     */
    private $user;

    public function __construct($user_id,$scenario=''){
        $this->user = User::model()->find('id=?',array($user_id));
        if($this->user !== null){
            $arr = array(
                'username' => $this->user->username,
                'display_name' => $this->user->display_name,
                'role' => $this->user->role,
                'email' => $this->user->email,
                'home_page' => $this->user->home_page,
            );
            $this->setAttributes($arr);
        }
        $this->setScenario($scenario);
        $this->init();
        $this->attachBehaviors($this->behaviors());
        $this->afterConstruct();
    }


    public function rules()
    {
        return array(
            array('display_name,username,email', 'required'),
            array('role', 'length', 'max' => 50),
            array('home_page', 'length', 'max' => 150),
            array('newpass,newpass1', 'length', 'max' => 255),
            array('newpass1','comparePass'),
        );
    }

    public function comparePass($attribute,$params){
        if($this->newpass){
            if($this->newpass1 != $this->newpass){
                $this->addError('newpass1','Nhập lại mật khẩu không đúng');
            }
        }
    }

    public function attributeLabels()
    {
        return array(
            'display_name' => 'Họ tên',
            'role' => 'Quyền',
            'home_page' => 'Website',
            'username' => 'Tài khoản',
            'newpass' => 'Mật khẩu mới',
            'newpass1' => 'Nhập lại mật khẩu mới',
            
        );
    }

    public function save()
    {
        //$user = User::model()->findByAttributes(array('display_name', 'role', 'email', 'home_page', 'username'), 'username=?', array($this->username));
        if ($this->user !== null && $this->validate()) {
            $arr = array(
                'display_name' => $this->display_name,
                'role' => $this->role,
                'email' => $this->email,
                'home_page' => $this->home_page,
            );
            if($this->newpass && $this->newpass == $this->newpass1){
                $arr['password'] = $this->user->hashPassword($this->newpass);
            }
            $this->user->setAttributes($arr);
            //var_dump($this->user->errors);die;
            if($this->user->save()){
                return true;
            }
        }
        return false;
    }
}
